import PageItem from './page_item.js';
import localforage from 'localforage';
import { httpReqeustApi } from '/@/api/linxyun/base/index.ts';
import { getPageFuncDefine } from './lxy_expression.js';
const httpRequest = httpReqeustApi();

// import { getPageInfo, getPageCpns } from './query'
import { createDDE_SA } from '/@/utils/stringUtil';

const DDE_SA = createDDE_SA(BASE_API.ENT_CODE || 0, 0, 0);
const headers = { 'DDE-SA': DDE_SA, 'Content-Type': 'application/json;charset=UTF-8' };
class Pages {
	_pages = {}; // pageid ---> lxy_page_define
	static _instance = null;
	static instance() {
		if (this._instance === null) {
			this._instance = new Pages();
		}

		return this._instance;
	}

	// 返回 lxy_page_define 对象
	async getPage(id) {
		console.log('gggggggggggid', id);
		// this.removeAll()
		const pageid = 'page' + id;
		// if (this._pages.hasOwnProperty(pageid)) {
		// 	return this._pages[pageid]
		// }
		console.log('[Debug][CustomPage]load page from local forage, id:', id);
		const page = await localforage.getItem(pageid);
		console.log('[Debug][CustomPage]Load from local forage: ', id, page);
		if (page !== null) {
			const page2 = new PageItem(page.pageInfo, page.pageCpns);
			this._pages[pageid] = page2;
			await getPageFuncDefine(id);
			return page2;
		}
		const page_define = await this.loadPage(id);
		if (page_define === null) {
			console.error('[Error][CustomPage]Page is not exist, pageid: ', id);
			return null;
		}

		console.log('[Debug][CustomPage]Load page from server, id:', id, page_define);
		const page1 = new PageItem(page_define.pageInfo, page_define.pageCpns);
		this._pages[pageid] = page1;
		await getPageFuncDefine(id);
		localforage.setItem(pageid, page_define);
		return page1;
	}

	check() {
		// 查询页面是否有更新,如果有更新，则调用 removeAll 删除所有缓存
		this.removeAll();
	}

	removeAll() {
		this._pages = {};
		localforage.clear();
	}
	removePage(id) {
		const pageid = 'page' + id;
		if (this._pages.hasOwnProperty(pageid)) {
			this._pages[pageid] = null;
		}
		localforage.removeItem(pageid);
	}

	// 返回加载到的 lxy_page_define 对象
	async loadPage(id) {
		console.log('iiiiiiidddddddd', id);
		// 从数据库中加载
		// const pageInfo = await getPageInfo(id)
		const page_data = await httpRequest.SyncPost('/eslithe/queryCustomPagesNew.action', { PageID: id }, {}, headers);
		console.log('custompages load page loadPage: ', page_data);
		const pageInfo = page_data.Records[0];
		const page_temp_data = await httpRequest.SyncPost(
			'/eslithe/queryCustomPageTempNew.action',
			{
				PageID: id,
				current: 1,
				limit: 400,
			},
			{},
			headers
		);
		console.log('custompages load page page_temp_data: ', page_temp_data);
		// const pageCpns = await getPageCpns(id)
		const pageCpns = page_temp_data.Records;
		return { pageInfo, pageCpns };
	}
}

export default Pages;
